package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketBrand;
import com.cskaoyan.market.service.AdminBrandService;
import com.cskaoyan.market.service.impl.AdminBrandServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

;


@WebServlet("/admin/brand/*")
public class AdminBrandController extends HttpServlet {

    private AdminBrandService adminBrandService = new AdminBrandServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/brand/", "");
        if ("list".equals(op)) {
            list(req,resp);
        }
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //TODO
        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        List<MarketBrand> brandList = adminBrandService.list(page, limit, sort, order, id, name);
        Object o = ResponseUtil.okList(brandList);
        resp.getWriter().println(JacksonUtil.writeValueAsString(o));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/brand/" , "");
        if ("create".equals(op)) {
            create(req,resp);
        } else if ("update".equals(op)) {
            update(req,resp);
        } else if ("delete".equals(op)) {
            delete(req,resp);
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = req.getReader().readLine();
        String id = JacksonUtil.parseString(requestBody, "id");
        adminBrandService.delete(id);
        Object ok = ResponseUtil.ok();
        resp.getWriter().println(JacksonUtil.writeValueAsString(ok));

    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //读取请求体中内容
        String requestBody = req.getReader().readLine();
        Integer id = Integer.valueOf(JacksonUtil.parseString(requestBody, "id"));
        String name = JacksonUtil.parseString(requestBody, "name");
        String desc = JacksonUtil.parseString(requestBody, "desc");
        String picUrl = JacksonUtil.parseString(requestBody, "picUrl");
        String floorPrice = JacksonUtil.parseString(requestBody, "floorPrice");
        LocalDateTime addTime = LocalDateTime.parse(JacksonUtil.parseString(requestBody, "addTime").replace(" ","T"));
        LocalDateTime updateTime = LocalDateTime.parse(JacksonUtil.parseString(requestBody, "updateTime").replace(" ","T"));
        Boolean deleted = Boolean.valueOf(JacksonUtil.parseString(requestBody, "deteted"));
        int i=adminBrandService.update(name,desc,picUrl,floorPrice,addTime,updateTime,deleted);
        Object o = ResponseUtil.ok(i);
        resp.getWriter().println(JacksonUtil.writeValueAsString(o));
    }

    private boolean create(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //TODO
        //读取请求体
        String requestBody = req.getReader().readLine();
        //System.out.println(requestBody);
        //ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        String name = JacksonUtil.parseString(requestBody, "name");
        String desc = JacksonUtil.parseString(requestBody, "desc");
        String picUrl = JacksonUtil.parseString(requestBody, "picUrl");
        String floorPrice = JacksonUtil.parseString(requestBody, "floorPrice");
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(desc) || StringUtils.isEmpty(floorPrice)) {
            Object o = ResponseUtil.fail(401, "参数不对");
            String s = JacksonUtil.writeValueAsString(o);
            resp.getWriter().println(s);
            return false;
        }else if (!floorPrice.matches("\\d+")){
//            Object o = ResponseUtil.fail(402, "参数值不对");
//            String s = JacksonUtil.writeValueAsString(o);
//            resp.getWriter().println(s);
            Object o = ResponseUtil.badArgument();
            resp.getWriter().println(JacksonUtil.writeValueAsString(o));
            return false;
        }

        MarketBrand marketBrand = adminBrandService.create(name, desc, picUrl, floorPrice);

        //获取当前时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String addTimeToString = marketBrand.getAddTime().format(formatter);
        String updateTimeToString = marketBrand.getUpdateTime().format(formatter);

        HttpSession session = req.getSession();
        session.setAttribute("brand",marketBrand);
        //String id = session.getId();

        Map<String,Object> data = new HashMap<>();
        data.put("id", marketBrand.getId());
        data.put("name", marketBrand.getName());
        data.put("desc", marketBrand.getDesc());
        data.put("floorPrice", marketBrand.getFloorPrice());
        data.put("addTime", addTimeToString);
        data.put("updateTime", updateTimeToString);
        if (!StringUtils.isEmpty(marketBrand.getPicUrl())) {
            data.put("picUrl", marketBrand.getPicUrl());
        }
        Object ok = ResponseUtil.ok(data);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ok));
        return true;
    }
}
